<?php
/**
 * Created by PhpStorm.
 * User: 悟能科技
 * Date: 2018/10/15
 * Time: 8:57
 */

namespace app\mobile\controller;


use app\common\model\Agent;
use app\common\model\CardGift;
use app\common\model\CardGiftPutOrder;
use app\common\model\CardGiftUserArea;
use app\common\model\CardUserGetGift;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardgifts extends Controller
{
    public function _init(){
        $param=request()->param();
        $card_id = request()->param('card_id');
        $appid = $this->getappid($card_id);
        $openid = Session::get($appid . "_openid");
        if (!$openid) {
            $option = $this->options($card_id);
            $WxObj = new Wxobjopen($option);
            //获取授权openid
            $userinfo = $WxObj->getOpenoauthAccessToken();
            //获取授权为空时向微信发送请求
            if (empty($userinfo)) {
                $request = request();
                $callback = $request->url(true);
                $url = $WxObj->getopenOauthCode($callback, '', 'snsapi_base');
                exit();
            } else {
                Session::set($option['authorizer_appid'] . "_openid", $userinfo['openid']);
                Session::set("card_openid", $userinfo['openid']);
            }
        }
//        $this->rec_login();
    }

    //修改会员信息
    public function edituserinfo(Request $request){
        $param = $request->param();
        $this->_init();
        $info = $this->getgiftuserinfo($param);
        if ($info['is_putgift'] == 1) {
            $CardGiftUserArea = new CardGiftUserArea();
            if ($request->isAjax()) {
                $param_post = $request->post();
//            return json($param_post);
                $map['openid'] = $info['openid'];
                $map['top_mid'] = $info['top_mid'];
                $area =  $CardGiftUserArea->where($map)->find();
                //END
                $data = $param_post;
                $data['openid'] = $info['openid'];
                $data['mid'] = $info['mid'];
                $data['top_mid'] = $info['top_mid'];
                $data['create_time'] = time();
                if ($area) {
                    $res = $CardGiftUserArea->allowField(true)->save($data,$map);
                }else{
                    $res = $CardGiftUserArea->allowField(true)->save($data);
                }
                if ($res) {
                    $rarr['code'] = 0;
                    $rarr['url'] = url('cardgifts/referorder', ['card_id' => $param['card_id'],'code'=>$info['code']]);
                    $rarr['message'] = '操作成功';
                } else {
                    $rarr['code'] = 9001;
                    $rarr['url'] = url('cardgifts/referorder', ['card_id' => $param['card_id'],'code'=>$info['code']]);
                    $rarr['message'] = '操作失败';
                }
                return json($rarr);
            } else {
                $map['card_id'] = $param['card_id'];
                $map['openid'] = $info['openid'];
                $area = $CardGiftUserArea->where($map)->find();
                //JSSDK
                $jssdk['wxjssdk'] = $this->getjssdk($param['card_id']);
                $jssdk['wxjssdk'] = json_encode($jssdk['wxjssdk']);
                $this->assign('jssdk',$jssdk);
                //END
                $info['name'] = $area['name'];
                $info['phone'] = $area['phone'];
                $info['area'] = $area['area'];
                $info['address'] = $area['address'];
                $this->assign('user', $area);
                $this->assign('info', $info);
                return $this->fetch();
            }
        }else{
           $this->redirect('cardgifts/giftorderinfo',['card_id'=>$param['card_id'],'code'=>$info['code']]);
        }
    }

    //提交订单
    public function referorder(Request $request){
        $param = $request->param();
        $CardGiftPutOrder = new CardGiftPutOrder();
//        halt($param);
        $this->_init();
        $info = $this->getgiftuserinfo($param);
        if ($info['is_putgift'] == 1) {
            $CardGiftUserArea = new CardGiftUserArea();
            $map['card_id'] = $param['card_id'];
            $map['openid'] = $info['openid'];
            $area = $CardGiftUserArea->where($map)->find();
            if ($area) {
                if ($request->isAjax()) {

                    $param_post = $request->post();
                    $param_post['openid'] = $info['openid'];
                    $param_post['area_id'] = $area['id'];
                    $param_post['create_time'] = time();
                    $res = $CardGiftPutOrder->allowField(true)->save($param_post);
                    $CardUserGetGift = new CardUserGetGift();
                    $CardUserGetGift->save(['is_putgift' => 2], ['code' => $info['code']]);
                    if ($res) {
                        $rarr['code'] = 0;
                        $rarr['url'] = url('cardgifts/giftorderinfo', ['card_id' => $param['card_id'], 'code' => $info['code']]);
                        $rarr['message'] = '操作成功';
                    } else {
                        $rarr['code'] = 9001;
                        $rarr['url'] = url('cardgifts/giftorderinfo', ['card_id' => $param['card_id'], 'code' => $info['code']]);
                        $rarr['message'] = '操作失败';
                    }
                    return json($rarr);
                } else {
                    $CardGift = new CardGift();
                    $CardGiftUserArea = new CardGiftUserArea();
                    $mapss['openid'] = $info['openid'];
                    $userarea = $CardGiftUserArea->where($mapss)->find();
                    $maps['card_id'] = $info['card_id'];
                    $cardinfo = $CardGift->where($maps)->field('title,prerogative,logo_url,brand_name')->find();
                    $info['title'] = $cardinfo['title'];
                    $info['prerogative'] = $cardinfo['prerogative'];
                    $info['logo_url'] = $cardinfo['logo_url'];
                    $info['brand_name'] = $cardinfo['brand_name'];
                    $this->assign('info', $info);
                    $this->assign('area', $userarea);
                    return $this->fetch();
                }
            } else {
                $this->redirect('cardgifts/edituserinfo', ['card_id' => $param['card_id'], 'code' => $info['code']]);
            }
        }else{
//            echo $info;
//            exit();
            $this->redirect('cardgifts/giftorderinfo',['card_id'=>$param['card_id'],'code'=>$info['code']]);
        }
    }

    //订单详情
    public function giftorderinfo(Request $request){
        $param = $request->param();
//        halt($param);
        $this->_init();
        $info = $this->getgiftuserinfo($param);
        $map['a.code'] = $info['code'];
        $map['a.openid'] = $info['openid'];
        $map['a.card_id'] = $info['card_id'];
        $CardGiftPutOrder = new CardGiftPutOrder();
        $info = $CardGiftPutOrder->alias('a')
            ->join('card_gift_user_area b','a.area_id=b.id')
            ->join('card_gift c','a.card_id=c.card_id')
            ->where($map)
            ->field('a.logistics_no,a.put_time,a.card_id,a.create_time,a.code,b.name,b.phone,b.area,b.address,c.title,c.prerogative,c.logo_url,c.brand_name')
            ->find();
        $info['logistics_no'] = $info['logistics_no'] == null ?'暂无':$info['logistics_no'];
        $this->assign('info',$info);
        return $this->fetch();
    }

    //获取卡号
    public function getusercode($arr){
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $map['card_id'] = $arr['card_id'];
        $codedata['encrypt_code'] = $arr['encrypt_code'];
        $resc = $WxObj->decryptCode($codedata);
        if ($resc['errcode'] == 0){
            $code = $resc['code'];
        }else{
            $code = 0;
        }
        return $code;
    }

    //获取礼品卡领取信息
    public function getgiftuserinfo($arr){
        $map['card_id'] = $arr['card_id'];
        if (isset($arr['encrypt_code'])){
            $map['code'] = $this->getusercode($arr);
        }else{
            $map['code'] = $arr['code'];
        }
        $appid = $this->getappid($arr['card_id']);
        $map['openid'] = Session::get($appid . '_openid');
        $map['card_type'] = 'GENERAL_CARD';
        $map['have'] = 1;
        $CardUserGet = new CardUserGetGift();
        $info = $CardUserGet->where($map)->field('id,mid,top_mid,c_id,openid,card_id,code,have,statu,is_putgift')->find();
        return $info;
    }


    //获取openid
    public function getappid($card_id)
    {
        $appid = Session::get($card_id . '_appid');
        if (!$appid) {
            $CardMember = new CardGift();
            $Momerchant = new Momerchant();
            $top_mid = $CardMember->where('card_id', $card_id)->value('top_mid');
            $map['id'] = $top_mid;
            $mab['id'] = $Momerchant->where($map)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $appid = $WxOpen->where($mab)->value('authorizer_appid');
        }
        return $appid;
    }

    //分享jssdk
    /*
     * $card_id
     *
     */
    private function getjssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'openAddress'
            ]
        ];
        return $wxJsSdk;
    }


    public function options($card_id)
    {
        $CardGift = new CardGift();
        $Merchant = new Merchant();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        $mid = $CardGift->where('card_id', $card_id)->value('mid');
        $map['id'] = $mid;
        $merchantinfo= $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config=$Agent->where(array('id'=>$merchantinfo['agent']))->field('component_token,component_encodingaeskey,component_appid,component_appsecret,open_ticket')->find();
        $users = $WxOpen->where($mab)->field('authorizer_appid,authorizer_refresh_token')->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}